package sourceagile.server.gitFileRepository;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;

public class GetGitFileContent {

	public static JSONObject jsonFileContent(String fileName, String projectName) {

		return jsonFileContent(readFile(fileName, projectName));
	}

	public static JSONObject jsonFileContent(String fileContent) {

		JSONObject entry = new JSONObject();

		try {

			entry.put("fileContent", fileContent);

		} catch (JSONException e) {

			e.printStackTrace();
		}

		return entry;
	}

	private static String readFile(String fileName, String projectName) {

		String projectPath = System.getProperty("java.io.tmpdir") + projectName;

		BufferedReader reader;

		StringBuilder stringBuilder = new StringBuilder();

		try {
			reader = new BufferedReader(new FileReader(projectPath + "/"
					+ fileName));

			String line = null;

			String ls = System.getProperty("line.separator");

			while ((line = reader.readLine()) != null) {

				stringBuilder.append(line);
				stringBuilder.append(ls);
			}

		} catch (IOException e) {

			e.printStackTrace();
		}

		return stringBuilder.toString();
	}

}
